package com.yss.reportworld.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;

import com.yss.common.core.constant.Constants;
import com.yss.common.core.constant.RequestDataHelper;
import com.yss.common.core.enums.YssStatusEnum;
import com.yss.common.core.exception.BusinessException;
import com.yss.common.core.utils.StringUtils;
import com.yss.common.core.utils.easyexecl.EasyExeclUtil;
import com.yss.common.core.utils.uuid.IdUtils;
import com.yss.common.security.utils.SecurityUtils;
import com.yss.reportworld.domain.DemandBugInfo;
import com.yss.reportworld.service.*;
import com.yss.reportworld.util.TableInfoUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yss.common.logger.annotation.Log;
import com.yss.common.logger.enums.BusinessType;
import com.yss.common.security.annotation.RequiresPermissions;
import com.yss.reportworld.domain.SqlScript;
import com.yss.common.core.web.controller.BaseController;
import com.yss.common.core.web.domain.AjaxResult;
import com.yss.common.core.web.page.TableDataInfo;

/**
 * SQL脚本管理Controller
 *
 * @author yss
 * @date 2023-03-27
 */
@RestController
@RequestMapping("/script")
public class SqlScriptController extends BaseController {
    @Autowired
    private ISqlScriptService sqlScriptService;
    @Autowired
    private IModularService modularService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IReportService reportService;
    @Autowired
    private IDemandBugInfoService demandBugInfoService;
    @Autowired
    private IWeComService weComService;

    /**
     * 查询SQL脚本管理列表
     */
    @RequiresPermissions("reportworld:script:list")
    @GetMapping("/list")
    public TableDataInfo list(SqlScript sqlScript) {
        startPage();
        List<SqlScript> list = sqlScriptService.selectSqlScriptList(sqlScript);
        return getDataTable(list);
    }

    /**
     * 初始化 加载
     */
    @RequiresPermissions("reportworld:script:list")
    @PostMapping("/init")
    public AjaxResult init(@RequestBody SqlScript sqlScript) {
        try {
            AjaxResult ajax = AjaxResult.success();
            // 当前版本的所有需求和BUG
            DemandBugInfo demandBugInfo = new DemandBugInfo();
            demandBugInfo.setHisVersion(sqlScript.getHisVersion());
            demandBugInfo.setVersion(sqlScript.getHisVersion());
            List<DemandBugInfo> list = demandBugInfoService.selectDemandBugInfoList(demandBugInfo);
            if (StringUtils.isEmpty(list)) {
                list = new ArrayList<>();
            }
            if (StringUtils.isNotEmpty(sqlScript.getHisVersion())) {
                DemandBugInfo info = new DemandBugInfo();
                info.setId("-1");
                info.setDemandBugNum("+");
                info.setDescription("新增需求/BUG");
                list.add(0, info);
            }
            ajax.put("demandBugInfoList", list);
            TableInfoUtil.handleTableVersion(sqlScript.getHisVersion()); // 替换表名
            //加载所属模块，客户，报表
            ajax.put("modularTree", modularService.selectModularTreeList());
            ajax.put("customerTree", customerService.selectCustomerTreeList());
            ajax.put("reportTree", reportService.selectReportTreeList());
            // 添加的版本号
            ajax.put("versions", sqlScriptService.getReductionVersion(true));
            ajax.put("reductionVersions", sqlScriptService.getReductionVersion(false));
            return ajax;
        } catch (Exception ex) {
            throw new BusinessException("初始化加载数据出错，请稍后重试！" + ex.getMessage());
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    /**
     * 导出SQL脚本管理列表
     */
    @RequiresPermissions("reportworld:script:export")
    @Log(title = "SQL脚本管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SqlScript sqlScript) {
        List<SqlScript> list = sqlScriptService.selectSqlScriptList(sqlScript);
        if (StringUtils.isNotEmpty(list)) {
            // 导出的时候带上需求BUG信息
            for (SqlScript script : list) {
                if (StringUtils.isNull(script) || StringUtils.isEmpty(script.getDemandBugId())) {
                    continue;
                }
                script.setExeclRemark(script.getRemark());
                DemandBugInfo demandBugInfo = demandBugInfoService.getById(script.getDemandBugId());
                if (StringUtils.isNull(demandBugInfo)) {
                    continue;
                }
                script.setDemandBugNum(demandBugInfo.getDemandBugNum());
                script.setDemandBugType(demandBugInfo.getDemandBugType());
                script.setDemandBugFsource(demandBugInfo.getDemandBugFsource());
                script.setDescription(demandBugInfo.getDescription());
            }
        }
        EasyExeclUtil.export(response, list, SqlScript.class);
    }

    @RequiresPermissions("reportworld:script:exportSql")
    @Log(title = "SQL脚本管理", businessType = BusinessType.EXPORT)
    @PostMapping("/exportSql")
    public void exportSql(HttpServletResponse response, SqlScript sqlScript) throws IOException {
        List<SqlScript> list = sqlScriptService.selectSqlScriptListSql(sqlScript);
        StringBuffer buffer = new StringBuffer();
        for (int i = list.size() - 1; i >= 0; i--) {
            if (StringUtils.isNull(list.get(i)) || StringUtils.isEmpty(list.get(i).getSqlScript())) {
                continue;
            }
            buffer.append(list.get(i).getSqlScript());
        }
        IOUtils.write(buffer.toString(), response.getOutputStream(), Constants.UTF8);
    }


    /**
     * 获取SQL脚本管理详细信息
     */
    @RequiresPermissions("reportworld:script:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(sqlScriptService.getById(id));
    }

    /**
     * 新增SQL脚本管理
     */
    @RequiresPermissions("reportworld:script:add")
    @Log(title = "SQL脚本管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SqlScript sqlScript) {
        sqlScript.setId(IdUtils.fastSimpleUUID());
        sqlScript.setCreateBy(SecurityUtils.getUsername());
        sqlScript.setCreateTime(new Date());
        sqlScript.setStatus(YssStatusEnum.WAITING_REVIEW.getCode());
        weComService.sendMessageTo(SecurityUtils.getLoginUser().getSysUser().getNickName() + "提交了SQL脚本，请尽快审批！");
        return toAjax(sqlScriptService.save(sqlScript));
    }

    /**
     * 修改SQL脚本管理
     */
    @RequiresPermissions("reportworld:script:edit")
    @Log(title = "SQL脚本管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SqlScript sqlScript) {
        sqlScript.setUpdateTime(new Date());
        sqlScript.setUpdateBy(SecurityUtils.getUsername());
        sqlScript.setStatus(YssStatusEnum.WAITING_REVIEW.getCode());
        if (StringUtils.isEmpty(sqlScript.getCustomerId())) {
            sqlScript.setCustomerId("");
        }
        if (StringUtils.isEmpty(sqlScript.getModularId())) {
            sqlScript.setModularId("");
        }
        if (StringUtils.isEmpty(sqlScript.getReportId())) {
            sqlScript.setReportId("");
        }
        return toAjax(sqlScriptService.updateById(sqlScript));
    }

    /**
     * 删除SQL脚本管理
     */
    @RequiresPermissions("reportworld:script:remove")
    @Log(title = "SQL脚本管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<String> ids) {
        return toAjax(sqlScriptService.removeByIds(ids));
    }

    /**
     * 审核SQL脚本管理
     */
    @RequiresPermissions("reportworld:script:process")
    @Log(title = "SQL脚本管理", businessType = BusinessType.REVIEW)
    @GetMapping("/processSqlScript/{ids}")
    public AjaxResult processSqlScript(@PathVariable List<String> ids) {
        AjaxResult ajax = AjaxResult.success();
        String msgInfo = sqlScriptService.processSqlScript(ids);
        ajax.put("msgInfo", msgInfo);
        return ajax;
    }

    /**
     * 退回SQL脚本管理
     */
    @RequiresPermissions("reportworld:script:rebut")
    @Log(title = "SQL脚本管理", businessType = BusinessType.FAIL_REVIEW)
    @PostMapping("/rebutSqlScript")
    public AjaxResult rebutSqlScript(@RequestBody SqlScript sqlScript) {
        AjaxResult ajax = AjaxResult.success();
        sqlScriptService.rebutSqlScript(sqlScript.getIdList(), sqlScript.getApprovalReason());
        return ajax;
    }


    /**
     * 检查SQl脚本
     */
    @Log(title = "SQL脚本管理", businessType = BusinessType.OTHER)
    @PostMapping("/checkSqlScript")
    public AjaxResult checkSqlScript(@RequestBody SqlScript sqlScript) {
        AjaxResult ajax = AjaxResult.success();
        try {
            String msgInfo = sqlScriptService.checkSqlScript(sqlScript);
            ajax.put("msgInfo", msgInfo);
            ajax.put("result", true);
        } catch (Exception ex) {
            ajax.put("msgInfo", ex.getMessage());
            ajax.put("result", false);
        }
        return ajax;
    }

    /**
     * 还原版本
     */
    @Log(title = "SQL脚本管理", businessType = BusinessType.OTHER)
    @GetMapping("/reductionData/{version}")
    public AjaxResult reductionData(@PathVariable String version) {
        AjaxResult ajax = AjaxResult.success();
        sqlScriptService.reductionData(version);
        return ajax;
    }
}
